package com.ruoyi.web.controller.wnjk.app.hospital;

import cn.hutool.jwt.JWT;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.pay.domain.dto.ConsultationOrderRequest;
import com.ruoyi.system.pay.domain.dto.PayRequestDTO;
import com.ruoyi.system.pay.domain.po.OrderQuery;
import com.ruoyi.system.pay.domain.po.PayOrder;
import com.ruoyi.system.pay.service.IPayService;
import com.ruoyi.system.wnjk.contents.Contents;
import com.ruoyi.system.wnjk.domain.po.WnjkConsultationFees;
import com.ruoyi.system.wnjk.domain.po.WnjkConsultationOrder;
import com.ruoyi.system.wnjk.domain.po.WnjkPatient;
import com.ruoyi.system.wnjk.domain.po.WnjkUser;
import com.ruoyi.system.wnjk.domain.vo.ConsultationOrderVO;
import com.ruoyi.system.wnjk.producer.DirectProducer;
import com.ruoyi.system.wnjk.service.IWnjkConsultationFeesService;
import com.ruoyi.system.wnjk.service.IWnjkConsultationOrderService;
import com.ruoyi.system.wnjk.service.IWnjkPatientService;
import com.ruoyi.system.wnjk.service.IWnjkUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/app/userinquiry")
public class AppUserInquiryOrderController {

    @Autowired
    private IWnjkPatientService wnjkPatientService;
    @Autowired
    private IWnjkConsultationFeesService wnjkConsultationFeesService;

    @Autowired
    private IPayService payService;

    @Autowired
    private IWnjkConsultationOrderService wnjkConsultationOrderService;

    @Autowired
    private DirectProducer directProducer;


    @GetMapping("/getUserInquiryOrderByUserId/{UserId}")
    public AjaxResult getUserInquiryOrderById(@PathVariable("UserId") Long UserId) {
        List<WnjkPatient> wnjkPatient = wnjkPatientService.selectWnjkPatientByUserId(UserId);
        return success(wnjkPatient);
    }

    //获取支付金额
    @GetMapping("/getFeeByType/{consultationType}")
    public AjaxResult getFeeByType(@PathVariable("consultationType") String consultationType) {
        WnjkConsultationFees wnjkConsultationFees = wnjkConsultationFeesService.findFeeByTypy(consultationType);
        return success(wnjkConsultationFees);
    }

    //订单支付
    @PostMapping("/alipay")
    public AjaxResult createConsultationOrder(@Valid @RequestBody ConsultationOrderRequest request
                                              ) {
        //校验token
        if (request.getUserId() == null) {
            return error("用户id不能为空");
        }

//        // 1. 校验token
////        if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith("Bearer ")) {
////            return error("无效的Token格式");
////        }
////
//        String token = authHeader.substring(7); // 移除"Bearer "前缀
//        try {
//            // 假设使用JWT解析token，你需要根据实际的token实现调整
//            Claims claims = Jwts.parser()
//                    .setSigningKey("yourSecretKey") // 替换为你的密钥
//                    .parseClaimsJws(token)
//                    .getBody();
//
//            // 从token中获取userId并与request中的userId比较
//            String tokenUserId = claims.getSubject();
//            if (request.getUserId() == null) {
//                return error("用户id不能为空");
//            }
//            if (!request.getUserId().equals(tokenUserId)) {
//                return error("Token与用户ID不匹配");
//            }
//
//            // 可选：校验token过期时间
//            Date expiration = claims.getExpiration();
//            if (expiration.before(new Date())) {
//                return error("Token已过期");
//            }
//        } catch (JwtException e) {
//            return error("无效的Token: " + e.getMessage());
//        }

        //校验订单id是否存在
        WnjkConsultationOrder wnjkConsultationOrder = wnjkConsultationOrderService.selectWnjkConsultationOrderByOrderId(request.getOrderId());
        if (wnjkConsultationOrder != null && wnjkConsultationOrder.getOrderStatus().equals("PAID")) {
            return error("订单已支付");
        }
        //生成订单id
        request.setOrderId(UUID.randomUUID().toString());
        WnjkConsultationOrder wnjkConsultationOrder1 = new WnjkConsultationOrder();
        wnjkConsultationOrder1.setOrderId(request.getOrderId());
        wnjkConsultationOrder1.setPatientId(request.getPatientId());
        wnjkConsultationOrder1.setUserId(request.getUserId());
        wnjkConsultationOrder1.setConsultationType(request.getConsultationTypes());
        wnjkConsultationOrder1.setOrderAmount(request.getOrderAmount());
        wnjkConsultationOrder1.setDescription(request.getDescription());
        wnjkConsultationOrder1.setDoctorId(request.getDoctorId());
        //创建时间
        wnjkConsultationOrder1.setConsultationTime(new Date());
        //支付方式
        wnjkConsultationOrder1.setPaymentMethod("支付宝");
        //写入数据库
        wnjkConsultationOrderService.insertWnjkConsultationOrder(wnjkConsultationOrder1);

        PayRequestDTO payRequestDTO = new PayRequestDTO();
        payRequestDTO.setOrderNumber(request.getOrderId());
        payRequestDTO.setSourceType(Contents.Pay.TYPE_WZ_INTERROGATION);
        payRequestDTO.setSourceId("支付宝");
        payRequestDTO.setAmount(request.getOrderAmount().toString());
        payRequestDTO.setSubject("问诊订单");
        payRequestDTO.setBody("问诊订单");
        String s = payService.unifiedPay(payRequestDTO);
        System.out.println(s);

        //发送消息给rabbitmq
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setOrderNumber(wnjkConsultationOrder1.getOrderId());
        orderQuery.setSourceType(Contents.Pay.TYPE_WZ_INTERROGATION);
        directProducer.sendRequest(orderQuery);

        return success(s);
    }



    @GetMapping("/order/{userId}")
    public AjaxResult getOrder(@PathVariable("userId") Long userId) {
        List<WnjkConsultationOrder> wnjkConsultationOrders = wnjkConsultationOrderService.selectWnjkConsultationOrderByUserId(userId);
        System.out.println(wnjkConsultationOrders);
        return success(wnjkConsultationOrders);
    }

    //继续支付
    @PostMapping("/continuePay")
    public AjaxResult continuePay(@Valid @RequestBody ConsultationOrderRequest request) {

        WnjkConsultationOrder wnjkConsultationOrder = wnjkConsultationOrderService.selectWnjkConsultationOrderByOrderId(request.getOrderId());
        if (wnjkConsultationOrder.getOrderId() != null && wnjkConsultationOrder.getOrderStatus().equals("待支付")) {
            wnjkConsultationOrder.setOrderStatus("待回答");
            wnjkConsultationOrderService.updateWnjkConsultationOrder(wnjkConsultationOrder); //更新订单状态

            wnjkConsultationOrder.setConsultationTime(new Date());

        }else if (wnjkConsultationOrder.getOrderId()==null|| wnjkConsultationOrder.getOrderStatus().equals("待回答")){
            return error("订单已支付");
        }
        PayRequestDTO payRequestDTO = new PayRequestDTO();
        payRequestDTO.setOrderNumber(wnjkConsultationOrder.getOrderId());
        payRequestDTO.setSourceType(Contents.Pay.TYPE_WZ_INTERROGATION);
        payRequestDTO.setSourceId("支付宝");
        payRequestDTO.setAmount(wnjkConsultationOrder.getOrderAmount().toString());
        payRequestDTO.setSubject("问诊订单");
        payRequestDTO.setBody("问诊订单");
        String s = payService.unifiedPay(payRequestDTO);
        System.out.println(s);


        return success(s);

    }

}

